package online.struts.chain.processor;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.action.RequestProcessor;
import org.apache.struts.chain.commands.AbstractSelectAction;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.chain.contexts.ServletActionContext;

import core.exception.PhysicalException;

/**
 * パス取得
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class SelectActionProcessor extends AbstractSelectAction {

	/**
	 * @see org.apache.struts.chain.commands.AbstractSelectAction
	 * #getPath(org.apache.struts.chain.contexts.ActionContext)
	 */
	@Override
	protected String getPath(final ActionContext context) {
		// キャスト
		if (!ServletActionContext.class.isInstance(context)) {
			LogManager.getLogger().error(context);
			throw new IllegalStateException(String.valueOf(context));
		}
		ServletActionContext sac = ServletActionContext.class.cast(context);

		// サーブレット名取得
		HttpServletRequest request = sac.getRequest();
		String path = Objects.toString(request.getAttribute(RequestProcessor.INCLUDE_SERVLET_PATH),
				request.getServletPath());

		int period = path.lastIndexOf('.');
		if (period < 0) {
			// パスインフォ取得
			String ipath = Objects.toString(
					request.getAttribute(RequestProcessor.INCLUDE_PATH_INFO),
					request.getPathInfo());
			if (!Objects.toString(ipath, "").isEmpty()) {
				return ipath;
			}
		}

		String prefix = context.getModuleConfig().getPrefix();
		if (!path.startsWith(prefix)) {
			String msg = sac.getActionServlet().getInternal().getMessage("processPath");
			LogManager.getLogger().warn(msg + " " + path);
			throw new PhysicalException("No action config found.", null);
		}

		path = path.substring(prefix.length());
		if (period >= 0) {
			int slash = path.lastIndexOf('/');
			if (period > slash) {
				path = path.substring(slash, period);
			} else {
				path = path.substring(0, period);
			}
		}

		return path;
	}
}
